<template>
  <!-- 主容器 -->
  <div class="uni-640-1400-box page">
    <!-- 页面输出 -->
    <div class="page__output outputBlock">
      <!-- 输出图像 -->
      <div
        class="outputBlock__image uni-shadow"
        ref="roleImgRef"
      >
        <ElImage
          fit="cover"
          class="w-h-full"
          :src="role.avatar"
        ></ElImage>
      </div>
      <!-- 输出消息 -->
      <div class="outputBlock__msg uni-shadow">
        <!-- 消息列表 -->
        <el-scrollbar :height="`${roleImgHeight}px`">
          <div
            v-for="item in chatMesssages"
            class="chatCard relative"
            :role="item.role"
          >
            <ChatMessageCard
              @load-complete="
                () => item.loadCompleteTask && item.loadCompleteTask()
              "
              :task="item.task"
            ></ChatMessageCard>
            <div
              style="font-size: 10px"
              class="absolute right-0 bottom-0 opacity-30 italic"
              v-if="item.role === 'Peer' && item.loadCompleteTask"
            >
              本回答由AI生成，内容仅供参考，请仔细甄别。
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <!-- 页面输入 -->
    <div class="page__input inputBlock">
      <!-- 输入栏 -->
      <div class="inputBlock__input">
        <ElInput
          class="w-h-full"
          type="textarea"
          placeholder="输入"
          :rows="5"
          :disabled="isDisabled"
          v-model="inputMessage"
        ></ElInput>
      </div>
      <!-- 发送按钮 -->
      <div class="inputBlock__button aspect-square flex flex-col">
        <ElSelectV2
          v-model="aiOption"
          :options="aiOptions"
        ></ElSelectV2>
        <ElButton
          class="w-full flex-1"
          :disabled="isDisabled || inputMessage == ''"
          @click="handleClickSend"
          >发送</ElButton
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { AiOption, Role } from "~/models/type";
import { AiOptions, Roles } from "~/models/data";
import { ChatMessageCard } from "#components";

definePageMeta({
  layout: "uni-layout",
});

// 角色图像引用
const roleImgRef = useTemplateRef("roleImgRef");
const { width: roleImgWidth, height: roleImgHeight } =
  useElementSize(roleImgRef);
// 聊天消息卡片属性
interface ChatMessageCardProps {
  task: Promise<string>;
  role: "Self" | "Peer";
  loadCompleteTask: Function | undefined | null;
}

const query = useRoute().query;

const roleIndex = query.index ? parseInt(query.index as string, 10) : 0; // 获取角色索引，默认为0

const role = Roles[roleIndex]; // 默认角色

// 聊天消息
const chatMesssages = reactive<ChatMessageCardProps[]>([]);
// 输入消息
const inputMessage = ref<string>("");

const aiOption = ref(AiOptions[0].ID); // 默认AI选项
const aiOptions = AiOptions.map((item) => ({
  value: item.ID,
  label: item.Name,
}));
aiOption.value = 0;
// 是否禁用发送按钮
const isDisabled = ref(false);
// 处理点击发送发送
const handleClickSend = () => {
  isDisabled.value = true;
  // 模拟发送消息
  const messageTask = new Promise<string>((resolve) => {
    setTimeout(() => {
      resolve(inputMessage.value);
    }, 0);
  });

  // 添加到消息列表
  chatMesssages.push({
    task: messageTask,
    role: "Self",
    loadCompleteTask:
      aiOption.value == 999
        ? handleReplyDeepSeekMessage
        : handleReplySimulatedMessage,
  });
};

// 处理回复DeepSeek消息
const handleReplyDeepSeekMessage = () => {
  isDisabled.value = true;

  const replyTask = new Promise<string>((resolve) => {
    const sendPromise = $fetch("/api/ai/sendMessage", {
      method: "POST",
      body: {
        messages: [
          { role: "system", content: role.description },
          { role: "user", content: inputMessage.value },
        ],
        model: "deepseek-chat",
      },
    });
    sendPromise
      .then((response) => {
        resolve(response ?? "NULL Value");
      })
      .catch((error) => {
        console.error("Error sending message:", error);
        resolve("Error sending message");
      });
  });

  chatMesssages.push({
    task: replyTask,
    role: "Peer",
    loadCompleteTask: () => {
      isDisabled.value = false; // 解除禁用
      inputMessage.value = ""; // 清空输入框
    },
  });
};

// 模拟消息索引
const simulatedMessageIndex = ref(-1);
// 处理回复模拟消息
const handleReplySimulatedMessage = () => {
  console.log(simulatedMessageIndex);

  if (simulatedMessageIndex.value >= role.messages.length) {
    simulatedMessageIndex.value = 0; // 重置索引
    ElNotification({
      title: "提示",
      message: "没有更多消息了",
      type: "warning",
    });
    isDisabled.value = false;
    return;
  }
  simulatedMessageIndex.value++;
  async function pushChatMsgArr(msgArr: string[], index: number = 0) {
    if (index == msgArr.length) {
      isDisabled.value = false;
      return;
    }

    let replyTask = new Promise<string>((resolve) => {
      setTimeout(() => {
        resolve(msgArr[index]);
      }, 1000);
    });

    chatMesssages.push({
      task: replyTask,
      role: "Peer",
      loadCompleteTask: () => {
        pushChatMsgArr(msgArr, index + 1);
      },
    });
  }
  // 推聊天消息数组
  pushChatMsgArr(role.messages[simulatedMessageIndex.value]);
  //
};

onMounted(async () => {
  await nextTick();

  // 输出一下自我介绍

  const replyTask = new Promise<string>((resolve) => {
    isDisabled.value = true;
    setTimeout(() => {
      resolve(role.introduction);
    }, 500);
  });
  chatMesssages.push({
    task: replyTask,
    role: "Peer",
    loadCompleteTask: () => {
      isDisabled.value = false; // 解除禁用
    },
  });
});
</script>

<style lang="scss" scoped>
@mixin block($block) {
  .#{$block} {
    @content;
  }
}
@mixin element($element) {
  &__#{$element} {
    @content;
  }
}
@mixin modifier($modifier) {
  &--#{$modifier} {
    @content;
  }
}

@include block(chatCard) {
  @apply m-4 p-6 flex;
  border-radius: 0.125rem;

  &[role="Self"] {
    background-color: #95ec69;
    @apply text-right justify-end;
  }
  &[role="Peer"] {
    background-color: #f4f6f9;
    @apply text-left justify-start;
  }
}

// 页面布局
@include block(page) {
  height: 100vh;
  background-color: var(--bg-secondly-60);
  backdrop-filter: blur(4px);

  @apply flex flex-col p-2;
  // @apply m-2;
  @include element(output) {
    background-color: var(--bg-primary);
    padding: 1rem;
    flex: 1;
  }
  @include element(input) {
    background-color: var(--bg-primary);
    padding: 1rem;
    height: 150px;
  }
}

// 输出布局
@include block(outputBlock) {
  display: flex;
  width: 100%;
  gap: 1rem;
  @include element(image) {
    width: 250px;
  }
  @include element(msg) {
    flex: 1;
    background-color: var(--bg-primary);
    backdrop-filter: blur(10px);
  }
}

// 输入布局
@include block(inputBlock) {
  display: flex;
  @include element(input) {
    flex: 1;
    height: 100%;
  }
  @include element(button) {
  }
}
</style>
